import 'dart:async';

import 'package:http/http.dart' as http;

import '../common/test_page.dart';

class ResponseTestPage extends TestPage {
  ResponseTestPage(super.title) {
    group('()', () {
      test('http.Response().body', () {
        var response = http.Response('Hello, world!', 200);
        expect(response.body, 'Hello, world!');
      });

      test('http.Response().bodyBytes', () {
        var response = http.Response('Hello, world!', 200);
        expect(
            response.bodyBytes,
            [72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33]);
      });

      test('测试http.Response()处理字符集与指定编码不符的情况', () {
        var response = http.Response('föøbãr', 200,
            headers: {'content-type': 'text/plain; charset=iso-8859-1'});
        expect(response.bodyBytes, [102, 246, 248, 98, 227, 114]);
      });
    });

    group('.bytes()', () {
      test('测试使用http.Response.bytes()设置主体情况', () {
        var response = http.Response.bytes([104, 101, 108, 108, 111], 200);
        expect(response.body, 'hello');
      });

      test('测试使用http.Response.bytes()设置bodyBytes情况', () {
        var response = http.Response.bytes([104, 101, 108, 108, 111], 200);
        expect(response.bodyBytes, [104, 101, 108, 108, 111]);
      });

      test('测试使用http.Response.bytes()时判断字符集类型情况', () {
        var response = http.Response.bytes([102, 246, 248, 98, 227, 114], 200,
            headers: {'content-type': 'text/plain; charset=iso-8859-1'});
        expect(response.body, 'föøbãr');
      });
    });

    group('.fromStream()', () {
      test('http.StreamedResponse()设置主体', () async {
        var controller = StreamController<List<int>>(sync: true);
        var streamResponse = http.StreamedResponse(controller.stream, 200, contentLength: 13);
        controller
          ..add([72, 101, 108, 108, 111, 44, 32])
          ..add([119, 111, 114, 108, 100, 33]);
        unawaited(controller.close());
        var response = await http.Response.fromStream(streamResponse);
        expect(response.body, 'Hello, world!');
      });

      test('http.StreamedResponse()设置bodyBytes', () async {
        var controller = StreamController<List<int>>(sync: true);
        var streamResponse = http.StreamedResponse(controller.stream, 200, contentLength: 5);
        controller.add([104, 101, 108, 108, 111]);
        unawaited(controller.close());
        var response = await http.Response.fromStream(streamResponse);
        expect(response.bodyBytes, [104, 101, 108, 108, 111]);
      });
    });
  }

}